from HashMapBase import HashMapBase
from UnsortedTableMap import UnsortedTableMap

class ChainHashMap(HashMapBase):
    """通过分离链表实现哈希表类"""

    def _bucket_getitem(self, j, k):
        bucket = self._table[j]
        if not bucket:
            raise KeyError('%s不存在' % k)
        return bucket[k]

    def _bucket_setitem(self, j, k, v):
        if not self._table[j]:
            self._table[j] = UnsortedTableMap()
        oldsize = len(self._table[j])
        self._table[j][k] = v
        if len(self._table[j]) > oldsize:
            self._n += 1

    def _bucket_delitem(self, j, k):
        bucket = self._table[j]
        if not bucket:
            raise KeyError('%s不存在' % k)
        del bucket[j]

    def __iter__(self):
        for bucket in self._table:
            if bucket:
                for key in bucket:
                    yield key

